<template>
  <el-tabs
    v-model="editableTabsValue"
    type="border-card"
    @tab-remove="removeTab"
    @tab-click="handleTabClick"
    class="tabs_style"
  >
    <el-tab-pane
      v-for="item in editableTabs"
      :key="item.name"
      :label="item.title"
      :name="item.name"
      closable
      style="color: #003f82"
    >
    </el-tab-pane>
    <el-scrollbar>
      <router-view v-slot="{ Component, route }">
        <keep-alive v-if="route.meta.keepAlive">
          <component :is="Component" />
        </keep-alive>
        <component v-else :is="Component" />
      </router-view>
    </el-scrollbar>
  </el-tabs>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { store } from "@/stores/store";

const editableTabs = ref([]);
const editableTabsValue = ref(null);
const router = useRouter();
const route = useRoute();
const excludedPaths = ["/circuit"];

// 用于跟踪 /AI/score 页面的参数变化
const aiScoreParams = ref(route.query);

// 初始化标签页
const initializeTabs = () => {
  const { name, path, matched } = route;
  const isCircuitChildRoute = matched.some(
    (m) =>
      (m.path === "/circuit" && name == "电路配置") ||
      (m.path === "/circuit" && name == "电路设置") ||
      (m.path === "/simulation" && name == "仿真演算") ||
      (m.path === "/results/simulationResults" && name == "仿真类型查询")
  );
  if (isCircuitChildRoute) {
    return;
  }
  if (!name || !path) return;

  // 特殊处理 /AI/score 路由，只保留一个标签页
  if (path === "/AI/score") {
    const existingTab = editableTabs.value.find((tab) => tab.path === path);
    if (!existingTab) {
      editableTabs.value.push({
        title: name || "评分",
        name: name || path,
        path: path,
      });
    }
  } else {
    // 对于其他路由，检查是否已经存在标签页中
    const existingTab = editableTabs.value.find((tab) => tab.path === path);
    if (!existingTab && !excludedPaths.includes(path)) {
      editableTabs.value.push({
        title: name || "未命名",
        name: name || path,
        path: path,
      });
    }
  }

  editableTabsValue.value = name || path; // 设置当前激活的标签页
};

// 监听路由变化来更新标签页
watch(
  () => router.currentRoute.value,
  () => {
    initializeTabs();
  },
  { immediate: true }
);

const reloadAIScorePage = () => {
  console.log("AI Score 页面参数发生变化，重新加载内容");
};

// 监听 /AI/score 路由的查询参数变化
watch(
  () => route.query, // 仅监听路由查询参数变化
  (newQuery) => {
    if (route.path === "/AI/score" && Object.keys(newQuery).length > 0) {
      const rowData = newQuery.rowData ? JSON.parse(newQuery.rowData) : null;
      store.dispatch("updateAiScoreData", rowData); // 更新 Vuex 状态
    }
  },
  { immediate: true, deep: true }
);

// 处理标签页点击事件
const handleTabClick = (tab) => {
  const tabPath = editableTabs.value.find(
    (t) => t.name === tab.props.name // 修改为 tab.props.name 以匹配 Element Plus 的属性
  )?.path;
  if (tabPath) {
    router.push(tabPath);
  }
};

// 处理标签页关闭事件
const removeTab = (targetName) => {
  const tabs = editableTabs.value;
  let activeTab = editableTabsValue.value;

  if (activeTab === targetName) {
    const prevTabIndex = tabs.findIndex((tab) => tab.name === targetName) - 1;
    activeTab = prevTabIndex >= 0 ? tabs[prevTabIndex].name : "";
    const prevTabPath =
      prevTabIndex >= 0 ? tabs[prevTabIndex].path : "/index/iIndex";
    router.push(prevTabPath);
  }
  editableTabs.value = tabs.filter((tab) => tab.name !== targetName);
  editableTabsValue.value = activeTab;

  if (editableTabs.value.length === 0) {
    router.push("/index/iIndex");
    editableTabs.value.push({
      title: "主页总览",
      name: "index",
      path: "/index/iIndex",
    });
    editableTabsValue.value = "index";
  }
};

onMounted(() => {
  initializeTabs();
});
</script>
